const db = uniCloud.database()

/**
 * @param {object}  params = {shop_id ,user_id,type }
 * @param {string}  shop_id (店铺管理员)
 * @param {string}  user_id
 * @param {number}  type 0||1
 */
module.exports = async function(params = {}) {
	const clientInfo = this.getUniversalClientInfo()
	const dbJQL = uniCloud.databaseForJQL({
		clientInfo
	})
	// 1. 设置users表的关联店铺_id
	let shop_id
	if (params.shop_id) {
		shop_id = params.shop_id;
		// await dbJQL.collection('uni-id-users').doc(params.user_id).update({shop_id});
	}
	// 2. 初始appID值(保留注册的appID，强制可以访问前端sogdia)
	let {
		data
	} = await dbJQL.collection('uni-id-users').doc(params.user_id).field('role,dcloud_appid').get()
	//加入sogdia并去重
	let dcloud_appid = Array.from(new Set([...data[0].dcloud_appid, this.wjfCommonConfig.appIds.sogdia]))
	//两个参数一起写入users表
	await dbJQL.collection('uni-id-users').doc(params.user_id).update({
		shop_id,
		dcloud_appid
	});
	// 3. 表添加一条初始化数据
	if (data[0].role) {
		Object.assign(params, {
			role: data[0].role
		})
	}
	let res = await db.collection('wjf-management-persons').add({
		...params,
		create_date: Date.now()
	})
	return {
		errCode: 0,
		errMsg: 'add-success'
	}
}